package middleware

import (
	"server/pkg/app"
	"server/pkg/errcode"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

// 拦截对低权限用户发来的请求
func JWT(rank int) gin.HandlerFunc {
	return func(c *gin.Context) {
		claims, code := parseToken(c)
		if claims.Rank < rank {
			code = errcode.NoPermission
		}

		if code != errcode.Success {
			response := app.NewResponse(c)
			response.ToErrorResponse(code)
			c.Abort()
			return
		}

		c.Next()
	}
}

// 从请求头中获取token并解析
func parseToken(c *gin.Context) (*app.Claims, *errcode.Error) {
	var token string
	var claims *app.Claims

	if s, exist := c.GetQuery("token"); exist {
		token = s
	} else {
		token = c.GetHeader("token")
	}

	code := errcode.Success
	if token == "" {
		code = errcode.InvalidParams
	} else {
		var err error
		claims, err = app.ParseToken(token)
		if err != nil {
			switch err.(*jwt.ValidationError).Errors {
			case jwt.ValidationErrorExpired:
				code = errcode.UnauthorizedTokenTimeout
			default:
				code = errcode.UnauthorizedTokenError
			}
		}
	}

	return claims, code
}
